package com.github.ghsea.framework.job.loadbalancer;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.github.ghsea.framework.job.common.Endpoint;
import com.github.ghsea.framework.job.common.EndpointChangedListener;
import com.github.ghsea.framework.job.core.JobServerBootstrap;
import com.github.ghsea.framework.job.core.JobServerKey;
import com.github.ghsea.framework.job.dao.JobAssignmentDao;
import com.github.ghsea.framework.job.support.ZkPath;

/**
 * 选择当前Job分配最少的JobServer
 * 
 * @author Administrator
 *
 */
@Component
public class MinAssignmentJobServerSelector implements JobServerSelector {

	@Autowired
	private JobAssignmentDao jobAssgnDao;

	public JobServerKey select(String appName, String jobName) {
		Map<String, Integer> serverKey2JobCnt = jobAssgnDao.countByJobServer();
		if (serverKey2JobCnt == null || serverKey2JobCnt.size() == 0) {
			// 随机选一个
			EndpointChangedListener epChangedListener = JobServerBootstrap.getServerNodeChangedListener();
			Random r = new Random();
			Endpoint randomEp = epChangedListener.all().get(r.nextInt(epChangedListener.all().size()));
			return new JobServerKey(randomEp.getIp(), randomEp.getPort());
		}

		Iterator<Entry<String, Integer>> serverKey2JobCntItr = serverKey2JobCnt.entrySet().iterator();
		Entry<String, Integer> first = serverKey2JobCntItr.next();
		String minAssgnServerKey = first.getKey();
		Integer minCnt = first.getValue();
		while (serverKey2JobCntItr.hasNext()) {
			Entry<String, Integer> next = serverKey2JobCntItr.next();
			if (minCnt > next.getValue()) {
				minAssgnServerKey = next.getKey();
			}
		}

		return ZkPath.node2ServerKey(minAssgnServerKey);
	}

}